package com.example.weathermvvm.ui.weather

import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.weathermvvm.MyOwnApplication
import com.example.weathermvvm.data.WeatherRepository
import com.example.weathermvvm.data.model.weather.Weather
import kotlinx.coroutines.launch

/**
 *
 * @Author： LJH
 * @Time： 2022/8/15
 * @description：
 */
class WeatherViewModel(private val repository: WeatherRepository):ViewModel() {

    var weather = MutableLiveData<Weather>()

    var bingPic = MutableLiveData<String>()

    var refreshing = MutableLiveData<Boolean>()

    var weatherInitialized = MutableLiveData<Boolean>()

    var weatherId = ""

    fun getWeatherInfo(){
        Log.e("WeatherViewModel","getWeatherInfo()...")
        launch({
            weather.value = repository.getWeather(weatherId)
            weatherInitialized.value = true
            Log.e("WeatherViewModel","getWeatherInfo():${weatherInitialized.value}")
        },{
            Toast.makeText(MyOwnApplication.context,it.message,Toast.LENGTH_SHORT).show()
            Log.e("WeatherViewModel","getWeatherInfo():${it.message}")
        })
        getBingPic(false)
    }

    fun onRefresh(){
        refreshWeather()
    }

    fun refreshWeather(){
        refreshing.value = true
        launch({
            weather.value = repository.refreshWeather(weatherId)
            refreshing.value = false
            weatherInitialized.value = true
        },{
            Toast.makeText(MyOwnApplication.context,it.message,Toast.LENGTH_SHORT).show()
            refreshing.value = false
        })
        getBingPic(true)
    }

    fun isWeatherCached() = repository.isWeatherCached()

    fun getCachedWeather() = repository.getWeatheredInfo()!!

    private fun getBingPic(refresh:Boolean){
        launch({
               bingPic.value = if (refresh) repository.refreshBingPic() else repository.getBingPic()
        },{
            Toast.makeText(MyOwnApplication.context,it.message,Toast.LENGTH_SHORT).show()
        })
    }


    private fun launch(block:suspend () -> Unit,error:suspend (Throwable) -> Unit) = viewModelScope.launch {
        try {
            block()
        }catch (e:Throwable){
            error(e)
        }
    }
}